package calao.contact.client;

import java.util.Iterator;
import java.util.Vector;

import com.google.gwt.user.client.Command;

import calao.client.ServiceCallback;
import calao.client.ui.HasDeferredLoading;
import calao.client.ui.NumberedListBox;
import calao.client.util.Arrays;

public class ContactBox 
extends NumberedListBox
implements HasDeferredLoading
{

	class FakeContact extends Contact {
		FakeContact(int id) {
			super(id);
		}
		public String getLabel() {
			return id>0? mod.text.contactX(id) : "--";
		}
	}
	
	final ContactMod mod = ContactMod.instance;

	final private Vector data = new Vector();
	final private int group;
	
	public ContactBox()
	{
		this(-1);
	}
	
	public ContactBox(int group)
	{
		this(group, -1, -1);
	}

	ContactBox(int group, int org, int level)
	{
		if (org!=-1 || (level!=0 && group!=-1)) {
			this.group = -1; // no need to check group: server does it
			mod.getService().listContacts(group, org, 1, new ServiceCallback() {
				public void onReturn(Object result) {
					Contact[] info = (Contact[])result;
					for (int i=0; i<info.length; i++) {
						if (accepts(info[i])) data.add(info[i]);
					}
				}
			});
		}
		else {
			this.group = group;
			Iterator iter = mod.listContacts();
			while (iter.hasNext()) {
				Contact info = (Contact)iter.next();
				if (accepts(info)) data.add(info);
			}
		}
	}
	
	protected boolean accepts(Contact info) 
	{
		return group==-1 || Arrays.contains(info.groups, group);
	}
	
	public void setNumberSelected(final long number)
	{
		// always defer to make sure items are loaded
		ServiceCallback.defer(new Command() {
			public void execute() {		
				if (getContact((int)number)==null) {
					data.add(getFirstSortableItem(), new FakeContact((int)number));
					setFirstSortableItem(getFirstSortableItem()+1);
				}
				ContactBox.super.setNumberSelected(number);
			}
		});
	}
	
	public void refresh()
	{
		// always defer to make sure items are loaded
		ServiceCallback.defer(new Command() {
			public void execute() {		
				ContactBox.super.refresh();
			}
		});
	}
	
	protected int getItemCount() 
	{
		return data.size();
	}

	protected long getItemNumber(int index) 
	{
		return getItemContact(index).id;
	}
	
	Contact getItemContact(int index)
	{
		return (Contact)data.get(index);
	}

	protected String getItemText(int index) 
	{
		return getItemContact(index).getLabel();
	}
	
	public static ContactBox newOrganizationContactBox(int org)
	{
		return new ContactBox(-1, org, -1);
	}
	
	public Contact getContact(int id)
	{
		for (int i=0; i<data.size(); i++) {
			Contact contact = (Contact)data.get(i);
			if (contact.id==id && !(contact instanceof FakeContact)) return contact;
		}
		return null;
	}

}
